package com.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class CookieUtil {
    /**
     * Cookie追加
     *
     * @return
     * @throws Exception
     */
    public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
        try {
            value = URLEncoder.encode(value, "utf-8");
            Cookie cookie = new Cookie(name, value);
            cookie.setHttpOnly(true);
            cookie.setSecure(true);
            cookie.setPath("/");
            cookie.setMaxAge(maxAge);
            response.addCookie(cookie);
        } catch (Exception e) {
            System.out.print(e.getMessage());
        }

    }

    /**
     * Cookie取得
     *
     * @return
     * @throws Exception
     */
    public static String getCookie(HttpServletRequest request, String name) {

        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    try {
                        return URLDecoder.decode(cookie.getValue(), "utf-8");
                    } catch (UnsupportedEncodingException e) {
                        return null;
                    }
                }
            }
        }
        return null;
    }

    public static void removeCookie(HttpServletResponse response, String name) {
        try {

            Cookie cookie = new Cookie(name, null);
            cookie.setHttpOnly(true);
            cookie.setSecure(true);
            cookie.setMaxAge(0);
            cookie.setPath("/");
            response.addCookie(cookie);
        } catch (Exception e) {
            System.out.print(e.getMessage());
        }

    }

    public static String getCity(HttpServletRequest request, String name) {

        String city = getCookie(request, name);
        if (StringUtils.isBlank(city)) {
            city = "杭州";
        }
        return city;
    }
}
